package com.ft.turorial.spring.boot.web.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ft.turorial.spring.boot.domain.User;

public class SessionUtil {
	
	static Logger log = LoggerFactory.getLogger(SessionUtil.class);
	/**
	 * 系统登录用户名
	 */
	public static final String SESSIONUSER = "sessionUser";

	private static ThreadLocal<HttpSession> session =new ThreadLocal<HttpSession>();
	
	//需要从拦截器set进来,使用时和session一样
	private static ThreadLocal<User> currentUser = new ThreadLocal<User>();
	
	/**
	 * 获取当前session的id
	 * @return
	 */
	public static String getSessionId() {
		return session.get().getId().toString();
	}
	
	public static final void setSession(HttpServletRequest request) {
		session.set(request.getSession());
	}
	public static final void setUser(User user) {
		session.get().setAttribute(SessionUtil.SESSIONUSER, user);
		currentUser.set(user);
	}

	public static final User getUser() {
		if (session == null) {
			return null;
		}
		
		Object u = session.get().getAttribute(SessionUtil.SESSIONUSER);
		if (u != null) {
			setUser((User) u);
		}
		
		//从缓存框架中取 比如redis、zookeeper	
		/*ZKCacheManager zkCache=SpringContextHolder.getBean(ZKCacheManager.class);
		if (zkCache == null ){
			log.warn("ZKCacheManager is null.");
			return null;
		}
		String sessionId=session.get().getId();
		log.debug("sessionId:"+sessionId);
		User cacheUser=zkCache.get(sessionId);
		if (cacheUser == null ) {
			return null;
		}
		setUser(cacheUser);
		*/
		return (User) u;
	}

	public static HttpSession getSession() {
		return session.get();
	}
	
	/**
	 * 从session获取对像
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T get(String key) {
		return (T)getSession().getAttribute(key);
	}
	
	/**
	 * 移出 key
	 * @param key
	 */
	public static void remove(String key) {
		getSession().removeAttribute(key);
	}
	
	/**
	 * 向session存入对像
	 * @param key
	 * @param value
	 */
	public static void set(String key,Object value) {
		getSession().setAttribute(key, value);
	}
	
}
